<?php

class TargetValidator extends sfValidatorBase
{
    /** delimitator intre id-urile apartamentelor */
    const APARTAMENT_DELIMITER = '-';

    public function configure($options = array(), $messages = array())
    {
        $this->setOption('required', true);

        $this->setMessage('required', 'Selectaţi apartamentele la care se distribuie cheltuiala.');
    }

    public function doClean($value)
    {
        // $value trebuie sa fie un array
        if (!is_array($value))
        {
            $value = explode(self::APARTAMENT_DELIMITER, $value);
        }

        // lista trebuie sa contina valori unice
        $value = array_unique($value);

        //// verific daca id-urile apartamentelor sunt valide

        $length = count($value);

        $criteria = new UserCriteria('BlocPeer');
        $having = $criteria->getNewCriterion('validator', $length);
        $criteria
            ->addAsColumn('validator', 'COUNT(*)')
            ->addJoin(ApartamentPeer::SCARA_ID, ScaraPeer::ID, Criteria::INNER_JOIN)
            ->addJoin(ScaraPeer::BLOC_ID, BlocPeer::ID, Criteria::INNER_JOIN)
            ->add(ApartamentPeer::ID, $value, Criteria::IN)
            ->addHaving($having);

        $stmt = ApartamentPeer::doSelectStmt($criteria);
        $result = $stmt->rowCount();
        if (!$result)
        {
            throw new sfValidatorError($this, 'required');
        }

        return $value;
    }
}
